package org.truenewx.tnxjee.repo.mybatis.enums.support;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Optional;

import com.baomidou.mybatisplus.annotation.EnumValue;
import org.truenewx.tnxjee.core.enums.support.DefaultEnumItemValueResolver;
import org.truenewx.tnxjee.core.util.BeanUtil;

public class MyBatisEnumItemValueResolver extends DefaultEnumItemValueResolver {

    private static final String FIELD_VALUE = "value";

    @Override
    public String getValue(Field field) {
        String value = super.getValue(field);
        if (value == null) {
            Optional<Field> optionalField = Arrays.stream(field.getDeclaringClass().getDeclaredFields())
                    .filter(f -> f.isAnnotationPresent(EnumValue.class)).findFirst();
            String valueFieldName = optionalField.map(Field::getName).orElse(FIELD_VALUE);
            try {
                Object fieldValue = field.get(null);
                Object valueFieldValue = BeanUtil.getFieldValue(fieldValue, valueFieldName);
                if (valueFieldValue != null) {
                    value = valueFieldValue.toString();
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return value;
    }

}
